package com.example.administrator.runbook.fragments.community.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.runbook.R;
import com.example.administrator.runbook.fragments.CommonFragment;
import com.example.administrator.runbook.fragments.community.activity.DetailActivity;
import com.example.administrator.runbook.fragments.community.adapter.HotListAdapter;
import com.example.administrator.runbook.fragments.community.model.Tweets;
import com.example.administrator.runbook.fragments.community.utils.AsyncHttpClientHelper;
import com.example.administrator.runbook.fragments.community.utils.DiskCache;
import com.example.administrator.runbook.fragments.community.utils.Log;
import com.example.administrator.runbook.fragments.community.utils.NetWork;
import com.example.administrator.runbook.fragments.community.utils.ParserData;
import com.jakewharton.disklrucache.DiskLruCache;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class HotFragment extends CommonFragment implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {

    private static final String url = "http://api.zhuishushenqi.com/user/twitter/hottweets";
    private static final String TAG = "123456";
    private ListView listView;
    private List<Tweets> list;
    private HotListAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    android.util.Log.i(TAG, "handleMessage: ");
                    if (msg.obj instanceof JSONObject) {
                        JSONObject obj = (JSONObject) msg.obj;
                        ParserData instance = ParserData.getInstance();
                        List<Tweets> hot = instance.getHot(obj);
                        list.clear();
                        list.addAll(hot);
                        adapter.notifyDataSetChanged();
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                    break;
                case 1:
                    if (msg.obj instanceof String) {
                        String obj = (String) msg.obj;
                        Toast.makeText(getContext(), obj, Toast.LENGTH_SHORT).show();
                        list.clear();
                        adapter.notifyDataSetChanged();
                        if (swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                    break;
                case 2:
                    onRefresh();
                    break;
            }
            return true;
        }
    });
    private View view;
    private LinearLayout linearLayout;

    public HotFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_hot, container, false);
        linearLayout = (LinearLayout) view.findViewById(R.id.image_failure_hot_fragment);
        listView = (ListView) view.findViewById(R.id.list_view_fragment_hot);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.srl_fragment_hot);
        list = new ArrayList<>();
        adapter = new HotListAdapter(getContext(), list);
        listView.setAdapter(adapter);
        initListener();
        initData();
        return view;
    }

    private void initData() {

        String md5 = DiskCache.getMD5(url);
        DiskLruCache cache = DiskCache.getDiskLruCache("json");
        try {
            final DiskLruCache.Snapshot snapshot = cache.get(md5);
            final StringBuilder sb = new StringBuilder();
            if (snapshot != null) {
                Log.i("snapshot");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("run");
                        try {
                            InputStream is = snapshot.getInputStream(0);
                            InputStreamReader isr = new InputStreamReader(is, "utf-8");
                            BufferedReader reader = new BufferedReader(isr);
                            String s;
                            while ((s = reader.readLine()) != null) {
                                sb.append(s);
                            }
                            Message message = handler.obtainMessage(0);
                            message.obj = new JSONObject(sb.toString());
                            Log.i(sb.toString());
                            handler.sendMessage(message);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else {
                handler.sendEmptyMessage(2);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initListener() {
        swipeRefreshLayout.setOnRefreshListener(this);
        listView.setOnItemClickListener(this);
    }

    @Override
    public String getTitle() {
        return "热门";
    }

    @Override
    public void onRefresh() {
        if (NetWork.isNetworkConnected(getContext())) {
            AsyncHttpClientHelper instance = AsyncHttpClientHelper.getInstance();
            instance.get(handler, url);
        } else {
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.setRefreshing(false);
            }
            ImageView imageView = new ImageView(getContext());
            imageView.setImageResource(R.drawable.network_bg);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            params.gravity = Gravity.CENTER;
            imageView.setLayoutParams(params);
            linearLayout.removeAllViews();
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            p.gravity = Gravity.CENTER;
            linearLayout.addView(imageView);
            Toast.makeText(getContext(), "网络开小差了", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getContext(), DetailActivity.class);
        Tweets tweets = list.get(position);
        Bundle bundle = new Bundle();
        bundle.putString("id", tweets.getId());
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
